Imports System.Collections.Generic
Imports Cdm.DataCore.LookupTables
Imports Cdm.DataCore.Budget

Partial Class BudgetOnlineEntry_ExpenditureEntry
    Inherits System.Web.UI.Page

    'Private SpendingPlanRowList As Hashtable
    Private CategoryHeaderList As Hashtable
    Private FormulaList As ArrayList
    Private FormulaPairings As ArrayList
    Private JavaScriptList As ArrayList
    Private CategoryTotalCostFields As ArrayList
    Private CategoryDateofServiceFields As ArrayList
    Private CategoryTotalJavaScript As ArrayList
    Private SpendingPlanTotalFields As ArrayList
    Private currentCategoryId As Integer
    Dim C_EDIT_EXISTING As String = "0"
    Dim C_COPY_AND_CREATE As String = "1"


    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        'SpendingPlanRowList = New Hashtable()
        CancelButton.Attributes.Add("onclick", "CancelChanges();")
        If Not Me.IsPostBack Then
            Dim currentParticipant As Cdm.DataCore.Entities.Participant = EntityController.GetParticipant()
            TitleLabel.Text = EntityController.ReplaceDisplayName("Expenditure Report for ") + currentParticipant.DisplayLastNameFirst
            JavaScriptList = New ArrayList()
            BindDropDowns()
            SetDefaultDates()
            Dim mm As MasterPageExpandable = Me.Master
            mm.HideHeader(False)
        End If
    End Sub

    Private Sub SetDefaultDates()
        Dim spendingPlanId As Integer = CInt(Me.SpendingPlanDropDownList.SelectedValue)
        Dim selectedPlan As SpendingPlan = SpendingPlan.Retrieve(spendingPlanId)
        Me.StartDateTextBox.Text = selectedPlan.StartDate.ToShortDateString()
        Me.EndDateTextBox.Text = selectedPlan.EndDate.ToShortDateString()

    End Sub

    Private Sub BindDropDowns()
        Dim participantId As Integer = EntityController.GetParticipant().ParticipantId

        Me.SpendingPlanDropDownList.DataSource = SpendingPlanGrid.ListApprovedByParticipant(participantId)
        SpendingPlanDropDownList.DataTextField = "EffectiveDates"
        SpendingPlanDropDownList.DataValueField = "SpendingPlanId"
        SpendingPlanDropDownList.DataBind()
    End Sub

    Protected Property SpendingPlanId() As Integer
        Get
            If ViewState("spendingplanid") Is Nothing Then
                Return 0
            Else
                Return CInt(ViewState("spendingplanid"))
            End If
        End Get
        Set(ByVal value As Integer)
            ViewState("spendingplanid") = value
        End Set
    End Property

    Public Property ItemList() As Hashtable
        Get
            If ViewState("itemlist") Is Nothing Then
                ViewState("itemlist") = New Hashtable()
            End If
            Return ViewState("itemlist")
        End Get
        Set(ByVal value As Hashtable)
            ViewState("itemlist") = value
        End Set
    End Property

    Private Function GetCategoryItems(ByVal categoryId As Integer) As List(Of ExpenditureReportItem)
        If ItemList.Item(categoryId) Is Nothing Then
            ItemList.Add(categoryId, ExpenditureReportItem.ListByCategory(Me.SpendingPlanId, categoryId, Me.StartDateTextBox.Text, Me.EndDateTextBox.Text))
        End If
        Return ItemList.Item(categoryId)
    End Function

    Private Sub BuildItemsFromScreen()
        ItemList.Clear()
        Dim rowNumber As Integer
        Dim itemId As Integer
        Dim budgetCategoryId As Integer
        Dim headerId As Integer
        Dim dateModified As DateTime

        For iCategory As Integer = 0 To Me.CategoryDataList.Items.Count - 1
            Dim catLabel As Label = CategoryDataList.Items(iCategory).FindControl("CategoryNameLabel")
            budgetCategoryId = CInt(catLabel.ToolTip)
            Dim CategoryRows As Repeater = CategoryDataList.Items(iCategory).FindControl("CategoryRowsRepeater")
            If Not CategoryRows Is Nothing Then
                For iCategoryRow As Integer = 0 To CategoryRows.Items.Count - 1
                    Dim rowLabel As Label = CategoryRows.Items(iCategoryRow).FindControl("RowNumberLabel")
                    If isRow(rowLabel) Then
                        rowNumber = CInt(rowLabel.Text)
                        dateModified = Convert.ToDateTime(rowLabel.ToolTip)
                    Else
                        rowNumber = -1
                        dateModified = Convert.ToDateTime("1/1/1980")
                    End If
                    Dim RowItems As Repeater = CategoryRows.Items(iCategoryRow).FindControl("RowItemsRepeater")
                    Dim saveTime As DateTime = dateModified
                    For iItem As Integer = 0 To RowItems.Items.Count - 1
                        Dim itemTextBox As TextBox = RowItems.Items(iItem).FindControl("ItemTextBox")
                        Dim itemLabel As Label = RowItems.Items(iItem).FindControl("ItemLabel")

                        If isRow(rowLabel) Then
                            Dim tooltipString As String() = itemTextBox.ToolTip.Split(";")
                            itemId = CInt(tooltipString(0))
                            headerId = CInt(tooltipString(1))
                        Else
                            itemId = 0
                            headerId = CInt(itemLabel.ToolTip)
                        End If


                        Dim saveItem As ExpenditureReportItem = New ExpenditureReportItem()
                        saveItem.ItemNumber = rowNumber
                        saveItem.SpendingPlanId = Me.SpendingPlanId
                        saveItem.ItemValue = itemTextBox.Text
                        saveItem.ExpenditureReportItemId = itemId
                        saveItem.BudgetCategoryHeaderId = headerId
                        'saveItem.BudgetCategoryHeaderId = budgetCategoryHeaderId
                        saveItem.LastModified = UserAuthorization.CurrentUser.LogonId
                        saveItem.DateModified = saveTime
                        AddItemToItemList(budgetCategoryId, saveItem)
                    Next


                Next
            End If
        Next


    End Sub

    Private Sub AddItemToItemList(ByVal categoryId As Integer, ByVal itm As ExpenditureReportItem)
        If ItemList(categoryId) Is Nothing Then
            ItemList.Add(categoryId, New System.Collections.Generic.List(Of ExpenditureReportItem)())
        End If
        Dim catList As System.Collections.Generic.List(Of ExpenditureReportItem) = ItemList(categoryId)
        catList.Add(itm)
    End Sub

    Private Sub RegisterJavaScript()
        Dim sb As New System.Text.StringBuilder()

        sb.AppendLine("<script language='javascript'>")
        sb.AppendLine("function UpdateCalcs()")
        sb.AppendLine("{")

        If Not JavaScriptList Is Nothing Then
            For iLine As Integer = 0 To JavaScriptList.Count - 1
                sb.AppendLine("     " + JavaScriptList(iLine) + ";")
            Next
        End If


        sb.AppendLine()
        sb.AppendLine("// Category Totals")
        If Not CategoryTotalJavaScript Is Nothing Then
            For iCat As Integer = 0 To CategoryTotalJavaScript.Count - 1
                sb.AppendLine(CategoryTotalJavaScript(iCat))
            Next
        End If

        sb.AppendLine()
        sb.AppendLine("// Spending Plan Total")
        sb.AppendLine(GetJavaScriptSumStatement(Me.SpendingPlanTotalTextBox.ClientID, SpendingPlanTotalFields, Nothing))
        sb.AppendLine()

        sb.AppendLine("}")
        sb.AppendLine("</script>")
        Me.javascriptLiteral.Text = sb.ToString()
    End Sub

    Private Sub WriteLine(ByVal line As String)
        Response.Write(line)
        Response.Write(Chr(13))
    End Sub

    Private Function GetCategoryHeader(ByVal headerId As Integer) As LuAdminBudgetCategoryHeader
        If CategoryHeaderList Is Nothing Then
            PopulateCategoryHeaderList()
        End If

        Return CategoryHeaderList(headerId)
    End Function

    Private Sub PopulateCategoryHeaderList()
        CategoryHeaderList = New Hashtable()
        Dim allHeaders As List(Of LuAdminBudgetCategoryHeader) = LuAdminBudgetCategoryHeader.ListExpenditureColumns()
        For i As Integer = 0 To allHeaders.Count - 1
            CategoryHeaderList.Add(allHeaders(i).BudgetCategoryHeaderId, allHeaders(i))
        Next
    End Sub
    Private Sub BindCategoryList()
        Dim categoryList As List(Of LuAdminBudgetCategory) = LuAdminBudgetCategory.ListForSpendingPlan()
        Me.CategoryDataList.DataSource = categoryList
        Me.CategoryDataList.DataBind()

        RegisterJavaScript()
        Page.RegisterStartupScript("onload", "<script language=""javascript"">UpdateCalcs(); OpenDivList();</script>")
    End Sub

    Protected Sub CategoryDataList_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataListItemEventArgs) Handles CategoryDataList.ItemDataBound
        CategoryTotalCostFields = New ArrayList()
        CategoryDateofServiceFields = New ArrayList()

        Dim currentCategory As LuAdminBudgetCategory = e.Item.DataItem
        Me.currentCategoryId = currentCategory.BudgetCategoryId
        Dim rowRepeater As Repeater = e.Item.FindControl("CategoryRowsRepeater")
        Dim itemList As List(Of ExpenditureReportItem) = GetCategoryItems(currentCategory.BudgetCategoryId)
        Dim rowList As ArrayList

        If Not itemList Is Nothing Then
            rowList = AddItemsToRows(itemList)
            rowRepeater.DataSource = rowList
            rowRepeater.DataBind()
        End If

        Dim categoryTotalTextBox As TextBox = e.Item.FindControl("CategoryTotalTextBox")
        'Write Javascript Category Total

        If CategoryTotalJavaScript Is Nothing Then
            CategoryTotalJavaScript = New ArrayList()
            SpendingPlanTotalFields = New ArrayList()
        End If
        Dim sumStatement As String = GetJavaScriptSumStatement(categoryTotalTextBox.ClientID, CategoryTotalCostFields, CategoryDateofServiceFields)
        If Not String.IsNullOrEmpty(sumStatement) Then
            CategoryTotalJavaScript.Add(sumStatement)
        End If
        SpendingPlanTotalFields.Add(categoryTotalTextBox.ClientID)
    End Sub

    Private Function GetJavaScriptSumStatement(ByVal totalFieldClientId As String, ByVal ClientIdList As ArrayList, ByVal DateOfServiceList As ArrayList) As String

        'Return empty if there are no Client Id List items.
        If ClientIdList Is Nothing Then Return ""
        If ClientIdList.Count = 0 Then Return ""

        Dim statement As String = String.Concat("document.getElementById('", totalFieldClientId, "').value=MoneyValue(")
        Dim plusSign As String = ""

        For i As Integer = 0 To ClientIdList.Count - 1
            If DateOfServiceList Is Nothing Then
                statement = String.Concat(statement, plusSign, "EvaluateValue(document.getElementById('", ClientIdList(i).ToString(), "').value)")
            Else
                statement = String.Concat(statement, plusSign, "EvaluateValueIfDateEntered('", ClientIdList(i).ToString(), "','", DateOfServiceList(i).ToString(), "')")
            End If

            plusSign = "+"
        Next

        statement = String.Concat(statement, ");")
        Return statement

    End Function

    Protected Sub CategoryRowsRepeater_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.RepeaterItemEventArgs)
        Dim rowItemsRepeater As Repeater = e.Item.FindControl("RowItemsRepeater")

        If Not rowItemsRepeater Is Nothing Then
            Dim currentRow As ExpenditureRow = e.Item.DataItem
            rowItemsRepeater.DataSource = currentRow.ItemList
            rowItemsRepeater.DataBind()
        End If

        Dim rowDescriptionDropDown As DropDownList = e.Item.FindControl("AddRowDropDownList")
        If Not rowDescriptionDropDown Is Nothing Then
            rowDescriptionDropDown.Items.Clear()
            rowDescriptionDropDown.DataSource = SpendingPlanItem.ListByDescription(Me.SpendingPlanId, currentCategoryId)
            rowDescriptionDropDown.DataTextField = "ItemValue"
            rowDescriptionDropDown.DataValueField = "BudgetItemNumber"
            rowDescriptionDropDown.DataBind()
            rowDescriptionDropDown.Items.Insert(0, New ListItem("<Blank>", "0"))
        End If

        Dim addRowButton As Button = e.Item.FindControl("AddRowButton")
        If Not addRowButton Is Nothing Then
            addRowButton.CommandArgument = currentCategoryId.ToString()
            AddHandler addRowButton.Click, AddressOf AddRowButton_Click
        End If
    End Sub

    Protected Sub RowItemsRepeater_DataBinding(ByVal sender As Object, ByVal e As System.EventArgs)
        FormulaList = New ArrayList()
        FormulaPairings = New ArrayList()
        Dim SpendingPlanTaxRate As Double
        Dim DaysInSpendingPlan As Integer
        Try
            GetSpendingPlanDetails(SpendingPlanTaxRate, DaysInSpendingPlan)
        Catch ex As Exception
            Exit Sub
        End Try


        FormulaPairings.Add(New ExpenditureFormulaPairing("TaxRate", SpendingPlanTaxRate.ToString()))
        FormulaPairings.Add(New ExpenditureFormulaPairing("[TaxRate]", SpendingPlanTaxRate.ToString()))
        FormulaPairings.Add(New ExpenditureFormulaPairing("[DaysInSpendingPlan]", DaysInSpendingPlan.ToString()))
        FormulaPairings.Add(New ExpenditureFormulaPairing("DaysInSpendingPlan", DaysInSpendingPlan.ToString()))
    End Sub

    Private Sub GetSpendingPlanDetails(ByRef taxRate As Double, ByRef days As Integer)
        Dim currPlan As SpendingPlan = SpendingPlan.Retrieve(Me.SpendingPlanId)
        Dim participantObject As Cdm.DataCore.Entities.Participant = EntityController.GetParticipant()


        If Not IsDate(currPlan.EndDate) Then
            PopupMessage1.ShowErrorMessage("Can not load spending Plan data", "Spending Plan must have an end date.  Please update the spending plan and return.")
            Throw New Exception("Spending Plan does not have an end Date")
        End If
        days = DateDiff(DateInterval.Day, currPlan.StartDate, currPlan.EndDate) + 1

        Try
            taxRate = Cdm.DataCore.Budget.FMSATaxRate.RetrieveByFmsaIdAndDate(participantObject.FMSAId, currPlan.StartDate).TaxRate
        Catch ex As Exception
            PopupMessage1.ShowErrorMessage("Can not load spending Plan data", "FMSA Tax Rate information not set up.")
            Throw ex
        End Try
    End Sub

    Protected Sub CategoryRowsRepeater_DataBinding(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim o As Object = sender
    End Sub


    Protected Sub RowItemsRepeater_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.RepeaterItemEventArgs)
        Dim currentItem As ExpenditureReportItem = e.Item.DataItem
        Dim currentHeader As LuAdminBudgetCategoryHeader = GetCategoryHeader(currentItem.BudgetCategoryHeaderId)
        Dim formulaDisplayName As String = String.Concat("[", currentHeader.DisplayName, "]")

        If e.Item.ItemIndex = 0 Then
            FormulaList.Add("//// Row " + currentItem.ItemNumber.ToString())
        End If

        Dim currentTextBox As TextBox = e.Item.FindControl("ItemTextBox")
        Dim currentLabel As Label = e.Item.FindControl("ItemLabel")

        If currentItem.ItemNumber = -1 Then
            'currentTextBox.Text = currentHeader.DisplayName
            'currentTextBox.BorderStyle = BorderStyle.None
            'currentTextBox.BackColor = Drawing.Color.LightGray
            ''currentTextBox.Columns = currentHeader.ColumnWidth
            'currentTextBox.TextMode = TextBoxMode.MultiLine
            'currentTextBox.Font.Size = FontUnit.Point(8)
            'currentTextBox.Rows = 2
            currentLabel.Visible = True
            currentTextBox.Visible = False
            currentLabel.Text = currentHeader.DisplayName
            currentTextBox.Columns = currentHeader.ColumnWidth
            currentLabel.Width = currentTextBox.Width
            Return
        End If

        Dim formulaClientId As String
        Dim align As String
        Select Case currentHeader.ItemFormat
            Case "integer", "decimal"
                formulaClientId = String.Concat(" parseFloat(document.getElementById('", currentTextBox.ClientID, "').value)")
                align = "right"
            Case "currency"
                formulaClientId = String.Concat(" parseFloat(document.getElementById('", currentTextBox.ClientID, "').value)")
                align = "right"
            Case Else
                formulaClientId = String.Concat(" document.getElementById('", currentTextBox.ClientID, "').value")
                align = "left"
        End Select

        If currentHeader.ItemFormat = "currency" Then
            currentLabel.Visible = True
            currentLabel.Text = "$"
        Else
            currentLabel.Visible = False
        End If



        FormulaPairings.Add(New ExpenditureFormulaPairing(formulaDisplayName, formulaClientId))
        If Not currentTextBox Is Nothing Then
            currentTextBox.Columns = currentHeader.ColumnWidth
            currentTextBox.ToolTip = String.Concat(CStr(currentItem.ExpenditureReportItemId), ";", CStr(currentItem.BudgetCategoryHeaderId))
            If currentHeader.Formula.Length > 0 Then
                'currentTextBox.Enabled = False
                currentTextBox.BackColor = Drawing.Color.Transparent
                currentTextBox.ForeColor = Drawing.Color.Black
                'currentTextBox.BorderStyle = BorderStyle.None
                currentTextBox.Style("text-align") = align
                Dim currentFormula As String
                If currentHeader.ItemFormat = "currency" Then
                    currentFormula = String.Concat(" document.getElementById('", currentTextBox.ClientID, "').value=MoneyValue(", currentHeader.Formula.Substring(1), ")")
                Else
                    currentFormula = String.Concat(" document.getElementById('", currentTextBox.ClientID, "').value=EvaluateValue(", currentHeader.Formula.Substring(1), ")")
                End If
                FormulaList.Add(currentFormula)
            Else
                currentTextBox.Enabled = True
                currentTextBox.Style("text-align") = align
                currentTextBox.BackColor = Drawing.Color.White
                currentTextBox.Attributes.Add("onchange", "UpdateCalcs();")
            End If
            AddValidator(currentItem, currentHeader, currentTextBox)
            If currentHeader.ItemFormat = "currency" Then
                currentTextBox.Text = currentTextBox.Text.Replace("$", "")
            End If
        End If

        If currentHeader.DisplayName = "Start Date" Then

        End If

        If currentHeader.IsTotalCostField Then
            AddJavaScriptStatements()
            CategoryTotalCostFields.Add(currentTextBox.ClientID)
        End If
        If currentHeader.IsDateOfService Then
            CategoryDateofServiceFields.Add(currentTextBox.ClientID)
        End If

    End Sub

    Public Function GetRowText(ByVal rowNumber As Object) As String
        If CInt(rowNumber) = -1 Then
            Return ""
        Else
            Return rowNumber.ToString()
        End If
    End Function


    Private Sub AddJavaScriptStatements()
        Dim statement As String

        For iList As Integer = 0 To FormulaList.Count - 1
            statement = FormulaList(iList)
            For iPairing As Integer = 0 To FormulaPairings.Count - 1
                Dim pair As ExpenditureFormulaPairing = FormulaPairings(iPairing)
                statement = statement.Replace(pair.DisplayName, pair.TextBoxClientId)
            Next
            statement = statement.Replace("If(", "ExcelIF(")
            statement = statement.Replace("IF(", "ExcelIF(")
            statement = statement.Replace("if(", "ExcelIF(")
            Dim ExcelIfIndex = statement.IndexOf("ExcelIF")
            If ExcelIfIndex > 0 Then
                Dim beforeStatement As String = statement.Substring(0, ExcelIfIndex)
                Dim afterStatement As String = statement.Substring(ExcelIfIndex).Replace("=", "==")
                statement = String.Concat(beforeStatement, afterStatement)
            Else
                'Dim beforeStatement As String = ""
                'Dim afterStatement As String = ""
                'Dim equalIndex As Integer = statement.IndexOf("=")
                'If equalIndex >= 0 Then
                'beforeStatement = statement.Substring(0, equalIndex)
                ''afterStatement = String.Concat("=EvaluateValue(", statement.Substring(equalIndex + 1), ")")
                'statement = String.Concat(beforeStatement, afterStatement)
                'End If


            End If
            If (JavaScriptList Is Nothing) Then
                JavaScriptList = New ArrayList()
            End If

            JavaScriptList.Add(statement)
        Next

    End Sub

    Private Sub AddValidator(ByVal itm As ExpenditureReportItem, ByVal hdr As LuAdminBudgetCategoryHeader, _
                                ByVal txt As TextBox)

        Select Case hdr.ItemFormat.ToLower()
            Case "date"
                Dim cal As New AjaxControlToolkit.CalendarExtender
                cal.ID = "dtExtender"
                cal.TargetControlID = txt.ID
                txt.Parent.Controls.Add(cal)
                'Case "decimal" ', "currency"  -- DO NOT ADD TO CURRENCY
                '    Dim compareDecimal As New CustomValidator()
                '    compareDecimal.ID = "compare_decimal"
                '    compareDecimal.ClientValidationFunction = "ValidateDecimal"
                '    compareDecimal.ErrorMessage = "This number needs to be numeric."
                '    compareDecimal.ControlToValidate = txt.ID
                '    compareDecimal.Display = ValidatorDisplay.None
                '    txt.Parent.Controls.Add(compareDecimal)

                'Dim vcoTwo As New AjaxControlToolkit.ValidatorCalloutExtender()
                'vcoTwo.ID = "vcoDecimal"
                'vcoTwo.TargetControlID = "compare_decimal"
                'vcoTwo.Width = "200"
                'txt.Parent.Controls.Add(vcoTwo)
            Case "integer"
                Dim compareInteger As New CustomValidator()
                compareInteger.ID = "compare_integer"
                compareInteger.ClientValidationFunction = "ValidateInteger"
                compareInteger.ErrorMessage = "This number needs to be an integer."
                compareInteger.ControlToValidate = txt.ID
                compareInteger.Display = ValidatorDisplay.None
                txt.Parent.Controls.Add(compareInteger)

                Dim vcoTwo As New AjaxControlToolkit.ValidatorCalloutExtender()
                vcoTwo.ID = "vcoInteger"
                vcoTwo.TargetControlID = "compare_integer"
                vcoTwo.Width = "200"
                txt.Parent.Controls.Add(vcoTwo)
            Case Else
                'text -do not validate
        End Select

        If hdr.DisplayName = "Item Code" Then
            Dim ItemCodeAutoComplete As New AjaxControlToolkit.AutoCompleteExtender
            ItemCodeAutoComplete.TargetControlID = txt.ID
            ItemCodeAutoComplete.ServicePath = "~/AJAX/AutoComplete.asmx"
            'ItemCodeAutoComplete.BehaviorID = "QuickSearchEx"
            ItemCodeAutoComplete.ServiceMethod = "GetItemCodes"
            ItemCodeAutoComplete.MinimumPrefixLength = 1
            ItemCodeAutoComplete.CompletionInterval = 200
            ItemCodeAutoComplete.CompletionSetCount = 10
            ItemCodeAutoComplete.CompletionListItemCssClass = "autocomplete_listItem"
            ItemCodeAutoComplete.CompletionListCssClass = "autocomplete_completionListElement"
            ItemCodeAutoComplete.CompletionListHighlightedItemCssClass = "autocomplete_highlightedListItem"


            txt.Parent.Controls.Add(ItemCodeAutoComplete)
        End If



        If hdr.DisplayName = "Service Code" Then
            Dim ServiceCodeAutoComplete As New AjaxControlToolkit.AutoCompleteExtender
            ServiceCodeAutoComplete.TargetControlID = txt.ID
            ServiceCodeAutoComplete.ServicePath = "~/AJAX/AutoComplete.asmx"
            'ServiceCodeAutoComplete.BehaviorID = "QuickSearchEx"
            ServiceCodeAutoComplete.ServiceMethod = "GetServiceCodes"
            ServiceCodeAutoComplete.MinimumPrefixLength = 1
            ServiceCodeAutoComplete.CompletionInterval = 200
            ServiceCodeAutoComplete.CompletionSetCount = 10
            ServiceCodeAutoComplete.CompletionListItemCssClass = "autocomplete_listItem"
            ServiceCodeAutoComplete.CompletionListCssClass = "autocomplete_completionListElement"
            ServiceCodeAutoComplete.CompletionListHighlightedItemCssClass = "autocomplete_highlightedListItem"


            txt.Parent.Controls.Add(ServiceCodeAutoComplete)
        End If

    End Sub

    Private Function AddItemsToRows(ByVal itemList As List(Of ExpenditureReportItem)) As ArrayList
        Dim CategoryRowList As New Hashtable()
        Dim returnArrayList As New ArrayList()
        Dim newRow As ExpenditureRow
        Dim rowNumber As Integer
        Dim rowKey As String
        Dim dateModifiedString As String
        For i As Integer = 0 To itemList.Count - 1
            rowNumber = itemList(i).ItemNumber
            dateModifiedString = itemList(i).DateModified.ToString("MMddyyhhmmss")
            rowKey = String.Concat(rowNumber.ToString(), "_", dateModifiedString)
            If Not CategoryRowList.ContainsKey(rowKey) Then
                newRow = New ExpenditureRow()
                newRow.RowNumber = rowNumber
                newRow.DateModified = itemList(i).DateModified.ToString()
                newRow.ItemList = New List(Of ExpenditureReportItem)
                CategoryRowList.Add(rowKey, newRow)
                'SpendingPlanRowList.Add(rowNumber, newRow)
                returnArrayList.Add(newRow)
            Else
                newRow = CategoryRowList.Item(rowKey)
            End If
            newRow.ItemList.Add(itemList(i))
        Next

        Return returnArrayList

    End Function

    Protected Sub SaveButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles SaveButton.Click
        SaveExpenditureReportItems()
    End Sub


    Protected Sub AddRowButton_Click(ByVal sender As Object, ByVal e As System.EventArgs)

        Dim addButton As Button = CType(sender, Button)
        Dim itemNumber As Integer = 0

        'Call BuildItemsFromScreen to Save the current items on the screen.
        BuildItemsFromScreen()
        Dim categoryId As Integer = CInt(addButton.CommandArgument)
        Dim rowDropDownList As DropDownList = addButton.Parent.FindControl("AddRowDropDownList")
        If CInt(rowDropDownList.SelectedValue) > 0 Then
            itemNumber = CInt(rowDropDownList.SelectedValue) + 1
        End If
        Dim newItems As List(Of ExpenditureReportItem) = ExpenditureReportItem.AddNewRow(Me.SpendingPlanId, categoryId, itemNumber, UserAuthorization.CurrentUser.LogonId)
        If Not ItemList.ContainsKey(categoryId) Then
            ItemList.Add(categoryId, newItems)
        Else
            Dim currentList As List(Of ExpenditureReportItem) = ItemList(categoryId)
            For i As Integer = 0 To newItems.Count - 1
                currentList.Add(newItems(i))
            Next
            ItemList(categoryId) = currentList
        End If

        BindCategoryList()
    End Sub

    Private Sub SaveExpenditureReportItems()
        Dim rowNumber As Integer
        Dim itemId As Integer
        Dim headerId As Integer

        Dim itemTransaction As New Gentle.Framework.Transaction()
        Try


            For iCategory As Integer = 0 To Me.CategoryDataList.Items.Count - 1
                Dim CategoryRows As Repeater = CategoryDataList.Items(iCategory).FindControl("CategoryRowsRepeater")
                If Not CategoryRows Is Nothing Then
                    For iCategoryRow As Integer = 0 To CategoryRows.Items.Count - 1
                        Dim rowLabel As Label = CategoryRows.Items(iCategoryRow).FindControl("RowNumberLabel")
                        If isRow(rowLabel) Then
                            rowNumber = CInt(rowLabel.Text)
                            Dim RowItems As Repeater = CategoryRows.Items(iCategoryRow).FindControl("RowItemsRepeater")
                            Dim saveTime As Date = DateTime.Now
                            For iItem As Integer = 0 To RowItems.Items.Count - 1
                                Dim itemTextBox As TextBox = RowItems.Items(iItem).FindControl("ItemTextBox")
                                Dim tooltipString As String() = itemTextBox.ToolTip.Split(";")
                                itemId = CInt(tooltipString(0))
                                headerId = CInt(tooltipString(1))
                                Dim saveItem As ExpenditureReportItem = New ExpenditureReportItem()
                                saveItem.ItemNumber = rowNumber
                                saveItem.SpendingPlanId = Me.SpendingPlanId
                                saveItem.ItemValue = itemTextBox.Text
                                saveItem.BudgetCategoryHeaderId = headerId
                                saveItem.ExpenditureReportItemId = itemId
                                saveItem.LastModified = UserAuthorization.CurrentUser.LogonId
                                saveItem.DateModified = saveTime
                                saveItem.PersistIfModified(itemTransaction)
                            Next

                        End If
                    Next
                End If
            Next

            itemTransaction.Commit()
            Me.PopupMessage1.ShowSuccessMessage("Payment Actvity has been saved.")

        Catch ex As Exception
            itemTransaction.Rollback()
            PopupMessage1.ShowErrorMessage("There was an error saving the Spending Plan Items", ex.Message)
            'If Not ex.InnerException Is Nothing Then
            ' Response.Write("<BR><BR>")
            ' Response.Write(ex.InnerException.Message)
            'End If
        End Try
    End Sub

    Private Function isRow(ByVal rowLabel As Label) As Boolean
        If rowLabel Is Nothing Then Return False
        If IsNumeric(rowLabel.Text) Then
            Return True
        Else
            Return False
        End If
    End Function

    Protected Sub GetPaymentsButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles GetPaymentsButton.Click
        'These are the option values in the SpendingPlanOption radio button list

        Me.SpendingPlanId = CInt(Me.SpendingPlanDropDownList.SelectedValue)

        Dim budgetId As Integer = SpendingPlan.Retrieve(Me.SpendingPlanId).BudgetId
        If Not VerifyDates() Then
            Exit Sub
        End If

        BindCategoryList()
        Me.TotalsPanel.Visible = True
        Me.CloseWindowLiteral.Text = ""
        Dim startDate As DateTime = CDate(Me.StartDateTextBox.Text)
        Dim endDate As DateTime = CDate(Me.EndDateTextBox.Text)
        Dim budgetedAmount As Single = Budget.SpendingPlanBudget(SpendingPlanId, startDate, endDate)
        Me.BudgetAmountTextBox.Text = budgetedAmount.ToString()
    End Sub

    Private Function VerifyDates() As Boolean
        Dim participantId As Integer = EntityController.GetParticipant().ParticipantId
        Dim selectedSpendingPlanId As Integer = CInt(SpendingPlanDropDownList.SelectedValue)

        '-------------------------------------------------
        ' Part One: verify that dates entered are valid
        '-------------------------------------------------
        If Not IsDate(Me.StartDateTextBox.Text) Or _
           Not IsDate(Me.EndDateTextBox.Text) Then
            Me.PopupMessage1.ShowErrorMessage("Invalid Entry", "Please enter a valid start date and end date.")
            Return False
        Else
            If CDate(EndDateTextBox.Text) < CDate(StartDateTextBox.Text) Then
                Me.PopupMessage1.ShowErrorMessage("Invalid Entry", "End Date can not be earlier than start date.")
                Return False
            End If
        End If
        '-----------------------------------------------------------------------------
        ' Part Two: Verify that a budget is selected whose dates are outside the newly
        ' selected date range
        ' ----------------------------------------------------------------------------
        Dim spendplanStartDate As DateTime = CDate(StartDateTextBox.Text)
        Dim spendplanEndDate As DateTime = CDate(EndDateTextBox.Text)
        Dim selectedPlan As SpendingPlan = SpendingPlan.Retrieve(selectedSpendingPlanId)
        If selectedPlan.StartDate > spendplanStartDate Or selectedPlan.EndDate < spendplanEndDate Then
            Dim errMsg As String = String.Format("Please Enter Dates within Spending Plan Range of {0} - {1}", _
                                         selectedPlan.StartDate.ToShortDateString(), selectedPlan.EndDate.ToShortDateString())
            Me.PopupMessage1.ShowErrorMessage("Dates outside Range", errMsg)

            Return False
        End If

        Return True

    End Function



    Protected Sub SpendingPlanDropDownList_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles SpendingPlanDropDownList.SelectedIndexChanged
        SetDefaultDates()
    End Sub
End Class


Public Class ExpenditureRow
    Private rowNumberValue As Integer
    Private dateModifiedValue As DateTime
    Private itemListValue As List(Of ExpenditureReportItem)

    Public Property RowNumber() As Integer
        Get
            Return rowNumberValue
        End Get
        Set(ByVal value As Integer)
            rowNumberValue = value
        End Set
    End Property

    Public Property DateModified() As DateTime
        Get
            Return dateModifiedValue
        End Get
        Set(ByVal value As DateTime)
            dateModifiedValue = value

        End Set
    End Property

    Public ReadOnly Property RowNumberDisplay() As String
        Get
            If RowNumber = -1 Then
                Return ""
            Else
                Return RowNumber.ToString()
            End If
        End Get
    End Property
    Public Property ItemList() As List(Of ExpenditureReportItem)
        Get
            If itemListValue Is Nothing Then
                itemListValue = New List(Of ExpenditureReportItem)
            End If
            Return itemListValue
        End Get
        Set(ByVal value As List(Of ExpenditureReportItem))
            itemListValue = value
        End Set
    End Property

    Public Sub New()

    End Sub
End Class

Public Class ExpenditureFormulaPairing
    Public DisplayName As String
    Public TextBoxClientId As String

    Public Sub New(ByVal displayNameValue As String, ByVal textBoxClientIdValue As String)
        DisplayName = displayNameValue
        TextBoxClientId = textBoxClientIdValue
    End Sub
End Class
